from subprocess import Popen, TimeoutExpired, PIPE , STDOUT
import os 
import time
import platform
sysSystem = platform.system()

wd = os.getcwd()
os.chdir(".")
comport = None



ESPFULSE = 'espefuse.exe'
ESPTOOL = 'esptool.exe'
ESPSECURE = 'espsecure.exe'

if sysSystem == 'Darwin' or sysSystem == 'Linux':
    import serialPort
    comport = serialPort.chickPortName()
    ESPFULSE = 'espefuse.py'
    ESPTOOL = 'esptool.py'
    ESPSECURE = 'espsecure.py'
else:
    import fandCom
    comport = fandCom.getComPort()
    if comport[:3] != 'com' or comport[:3] != 'COM':
        comport = None

# loader = 'bootloader-0x1000.bin'
# partitions = 'partitiontable-0x8000.bin'
# mbin = 'micropython-0x10000.bin'
app='bootapp-0xe000.bin'
loader='mkloader-0x1000.bin'
partitions='mkp-0x8000.bin'
mbin='mk-0x10000.bin'

baseBinPth = 'bin'
ecodeOut = 'ecodeout'

logtxt = ''

def saveLog(data):
    f = open('log.txt','w')
    f.write(logtxt)
    f.close()

def runCMDAndOUT(cmd,code="utf8"):
    global logtxt
    print(cmd)
    process = Popen(cmd, shell=True, encoding='utf-8', stdin=PIPE, stdout=PIPE, stderr=STDOUT)
    while process.poll() is None:
        line = process.stdout.readline()
        line = line.strip()
        if line:
            print(line)
            logtxt += line + '\n'

def runCMD(cmd):
    print('-'*10)
    print(cmd)
    print('-'*10)
    with Popen(args=cmd, shell=True, encoding='utf-8', stdin=PIPE, stdout=PIPE, stderr=PIPE) as proc:
        os.chdir(wd)
        try:
            stdin = proc.stdin
            # 以\n结束，程序才能判断这是一次完整的读取 效果和`'1\n2\n'`相同
            stdin.write('\n')
            # 将输入从缓存刷新到子进程中
            stdin.flush()
            time.sleep(1)
            s = proc.stdout.readlines()
            for i,v in enumerate(s):
                print(v)
            time.sleep(1)
            return True
        except TimeoutExpired:
            proc.kill()
            return False

def uploadEbins():
    #烧写加密后的flash固件
    if not comport:
        print('not find com port')
        return
    cmd  = ESPTOOL + ' --chip esp32 --baud 460800 --before default_reset --after hard_reset write_flash -z --flash_mode dio --flash_freq 80m --flash_size detect 0xe000 e-%s 0x1000 e-%s 0x10000 e-%s 0x8000 e-%s'%(app,loader,mbin,partitions)
    runCMDAndOUT(cmd)


def resetDevice():
    cmd = ESPTOOL + ' run'
    runCMDAndOUT(cmd)

def eraseFlash():
    cmd = ESPTOOL + ' erase_flash'
    runCMDAndOUT(cmd)

def main():
    eraseFlash()
    time.sleep(1)
    uploadEbins()
    time.sleep(3)
    resetDevice()
def test():
    # resetDevice()
    uploadEbins()

if __name__ == '__main__':
    main()
    # test()